import { Injectable } from "@nestjs/common";
import { CreateRoleMenuDto } from "./dto/create-role-menu.dto";
import { UpdateRoleMenuDto } from "./dto/update-role-menu.dto";
import { ResultData } from "@/common/utils/result";
import { RoleMenu } from "@/modules/role-menu/entities/role-menu.entity";
import { Repository } from "typeorm";
import { InjectRepository } from "@nestjs/typeorm";

@Injectable()
export class RoleMenuService {
    constructor(
        @InjectRepository(RoleMenu)
        private readonly roleMenuRepository: Repository<RoleMenu>
    ) {
    }
    
    create(createRoleMenuDto: CreateRoleMenuDto) {
        return "This action adds a new roleMenu";
    }
    
    findAll() {
        return `This action returns all roleMenu`;
    }
    
    findOne(id: number) {
        return `This action returns a #${id} roleMenu`;
    }
    
    update(id: number, updateRoleMenuDto: UpdateRoleMenuDto) {
        return `This action updates a #${id} roleMenu`;
    }
    
    remove(id: number) {
        return `This action removes a #${id} roleMenu`;
    }
    
    async roleAddMenu({ roleId, menuIds }) {
        // 删除所有再新增
        await this.roleMenuRepository.delete({ roleId });
        return ResultData.ok(
            await this.roleMenuRepository.save(
                menuIds.map(v => ({ roleId: roleId, menuId: v }))
            )
        );
    }
    
    async getMenuIdByRoleId({ roleId }) {
        const res = await this.roleMenuRepository.find({ where: { roleId }, relations: ["menu"] });
        
        return ResultData.ok(
            res.map(v => {
                // 判断是否又children
                return {
                    menuId: v.menuId,
                    parentId: v.menu.parentId,
                    hasChildren: res.some(m => v.menuId === m.menu.parentId)
                };
            })
        );
    }
}
